package com.scwatch.core.web.back;

import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.Node;
import com.scwatch.core.domain.Site;
import com.scwatch.core.domain.User;
import com.scwatch.core.fulltext.InfoFulltextGenerator;
import com.scwatch.core.fulltext.SpecialFulltextGenerator;
import com.scwatch.core.html.HtmlGenerator;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.ModelService;
import com.scwatch.core.service.NodeQueryService;
import com.scwatch.core.service.OperationLogService;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.Context;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.scwatch.core.constant.Constants.*;

/**
 * GenerationController
 * 生成静态数据
 * @author gjl
 * 
 */
@Controller
@RequestMapping("/core/generation")
public class GenerationController {
	private static final Logger logger = LoggerFactory.getLogger(GenerationController.class);

	@RequiresPermissions("core:generation:html_index")
	@RequestMapping("html_index.do")
	public String htmlIndex(HttpServletRequest request, org.springframework.ui.Model modelMap) {
		return "core/generation/html_index";
	}

	@RequiresPermissions("core:generation:html_submit")
	@RequestMapping("make_all_html.do")
	public String makeAllHtml(HttpServletRequest request, RedirectAttributes ra) {
		Site site = Context.getCurrentSite();
		Integer userId = Context.getCurrentUserId();
		htmlGenerator.makeAll(site.getId(), site.getName(), userId, false);
		logService.operation("opr.html.makeAll", site.getName(), null, site.getId(), request);
		logger.info("make all HTML. name={}", site.getName());
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}

	@RequiresPermissions("core:generation:html_submit")
	@RequestMapping("one_key_enable.do")
	public String oneKeyEnable(HttpServletRequest request, RedirectAttributes ra) {
		Site site = Context.getCurrentSite();
		modelService.oneKeyEnableHtml(site.getId());
		logService.operation("html.oneKeyEnable", site.getName(), null, site.getId(), request);
		logger.info("one key enable. name={}", site.getName());
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}
	
	@RequiresPermissions("core:generation:html_submit")
	@RequestMapping("one_key_disable.do")
	public String oneKeyDisable(HttpServletRequest request, RedirectAttributes ra) {
		Site site = Context.getCurrentSite();
		modelService.oneKeyDisableHtml(site.getId());
		logService.operation("html.oneKeyEnable", site.getName(), null, site.getId(), request);
		logger.info("one key enable. name={}", site.getName());
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}

	@RequiresPermissions("core:generation:html_submit")
	@RequestMapping("make_home_html.do")
	public String makeHomeHtml(HttpServletRequest request, RedirectAttributes ra) {
		Integer siteId = Context.getCurrentSiteId();
		Node node = nodeQuery.findRoot(siteId);
		if (node != null) {
			htmlService.makeNode(node.getId());
			logService.operation("opr.html.makeHome", node.getName(), null, node.getId(), request);
			logger.info("make home HTML. name={}", node.getName());
		}
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}

	@RequiresPermissions("core:generation:html_submit")
	@RequestMapping("delete_home_html.do")
	public String deleteHomeHtml(HttpServletRequest request, RedirectAttributes ra) {
		Integer siteId = Context.getCurrentSiteId();
		Node node = nodeQuery.findRoot(siteId);
		if (node != null) {
			htmlGenerator.deleteHtml(node);
			logService.operation("opr.html.deleteHome", node.getName(), null, node.getId(), request);
			logger.info("delete home HTML. name={}", node.getName());
		}
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}

	@RequiresPermissions("core:generation:html_submit")
	@RequestMapping("make_node_html.do")
	public String makeNodeHtml(Integer nodeId, @RequestParam(defaultValue = "true") boolean includeChildren,
			HttpServletRequest request, RedirectAttributes ra) {
		Integer siteId = Context.getCurrentSiteId();
		Integer userId = Context.getCurrentUserId();
		String nodeName = null;
		if (nodeId != null) {
			Node node = nodeQuery.get(nodeId);
			Backends.validateDataInSite(node, siteId);
			nodeName = node.getDisplayName();
		}
		htmlGenerator.makeNode(siteId, nodeId, nodeName, includeChildren, userId,null);
		logService.operation("opr.html.makeNode", nodeName, null, nodeId, request);
		logger.info("make node HTML. name={}", nodeName);
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}

	@RequiresPermissions("core:generation:html_submit")
	@RequestMapping("make_info_html.do")
	public String makeInfoHtml(Integer nodeId, @RequestParam(defaultValue = "true") boolean includeChildren,
			HttpServletRequest request, RedirectAttributes ra) {
		Integer siteId = Context.getCurrentSiteId();
		Integer userId = Context.getCurrentUserId();
		String nodeName = null;
		if (nodeId != null) {
			Node node = nodeQuery.get(nodeId);
			Backends.validateDataInSite(node, siteId);
			nodeName = node.getDisplayName();
		}
		htmlGenerator.makeInfo(siteId, nodeId, nodeName, includeChildren, userId);
		logService.operation("opr.html.makeInfo", nodeName, null, nodeId, request);
		logger.info("make info HTML. name={}", nodeName);
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}

    /**
     * 生成全文索引
     * @param nodeId 栏目
     * @param request
     * @param ra
     * @return 结果页面
     */
	@RequiresPermissions("core:generation:fulltext_submit")
	@RequestMapping("fulltext_submit.do")
	public String fulltextSubmit(Integer nodeId, HttpServletRequest request, RedirectAttributes ra) {
		Integer siteId = Context.getCurrentSiteId();
		Integer userId = Context.getCurrentUserId();
		Node node = null;
		String nodeName = null;
		if (nodeId != null) {
			node = nodeQuery.get(nodeId);
			Backends.validateDataInSite(node, siteId);
			nodeName = node.getName();
		}
        if(node!=null && Constants.SPECIAL_MANAGEMENT.equals(node.getNodeModel().getFlag())){
            specialFulltextGenerator.addDocument(siteId,userId);
        }else{
		    infoFulltextGenerator.addDocument(siteId, node, userId);
        }
		logService.operation("opr.fulltext.make", nodeName, null, nodeId, request);
		logger.info("make fulltext. name={}", nodeName);
		ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
		return "redirect:html_index.do";
	}


    /**
     * 根据栏目生成静态数据
     * @param queryNodeId 栏目
     * @param returnUrl 返回url
     * @param ra
     * @param jspUrl jsp页面url
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationDataByNode.do")
//    @RequiresRoles("super")
    @RequiresPermissions(value = {
            "core:sinatv:generationTv",
            "core:sinatv:generationTv01",
    },logical = Logical.OR)
    public String generationDataByNode(Integer queryNodeId,String returnUrl,RedirectAttributes ra,
                                       String jspUrl,
                                       HttpServletRequest request,org.springframework.ui.Model modelMap) {
        Integer nodeId=queryNodeId;
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        String ip = Servlets.getRemoteAddr(request);
        Node queryNode=null;
        if(queryNodeId!=null){
            queryNode=nodeQuery.get(queryNodeId);

            if(Constants.MODEL_FLAG_NEWSFLASH.equals(queryNode.getNodeModel().getFlag())||
                    Constants.MODEL_FLAG_BIGNEWS.equals(queryNode.getNodeModel().getFlag())){
                queryNode=queryNode.getParent();
                queryNodeId=queryNode.getId();
                htmlGenerator.makeInfo(site.getId(), queryNodeId,queryNode.getName(),true, user.getId());
                htmlGenerator.makeNode(site.getId(), queryNodeId,queryNode.getName(), true, user.getId(),null);
                logService.operation("opr.generationDataByNode", queryNode.getName(), null,queryNodeId,ip,user.getId(), site.getId());
                logger.info("generationDataByNode json Info, node={}.",queryNode.getName());
            }else if(Constants.MODEL_FLAG_ANCHOR_NODE.equals(queryNode.getNodeModel().getFlag())||
                    Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL.equals(queryNode.getNodeModel().getFlag())){
                Node parent = queryNode.getParent();
                while (parent != null) {
                    queryNodeId = queryNode.getId();
                    if (Constants.MODEL_FLAG_ANCHOR.equals(parent.getNodeModel().getFlag())) {
                        htmlGenerator.makeNode(site.getId(), queryNodeId, queryNode.getName(), true, user.getId(), null);
                        logService.operation("opr.generationDataByNode", queryNode.getName(), null, queryNodeId, ip, user.getId(), site.getId());
                        logger.info("generationDataByNode json Info, node={}.", queryNode.getName());

                        //生成anchor.json
                        htmlGenerator.makeNode(site.getId(), parent.getId(), parent.getName(), false, user.getId(), null);
                        logService.operation("opr.generationDataByNode", parent.getName(), null, queryNodeId, ip, user.getId(), site.getId());
                        logger.info("generationDataByNode json Info, node={}.", parent.getName());

                        break;
                    } else {
                        parent = parent.getParent();
                    }
                }
            }else if(Constants.MODEL_FLAG_ANCHOR_DYNAMIC.equals(queryNode.getNodeModel().getFlag())){
                htmlGenerator.makeNode(site.getId(), queryNodeId, queryNode.getName(), true, user.getId(), null);
                logService.operation("opr.generationDataByNode", queryNode.getName(), null, queryNodeId, ip, user.getId(), site.getId());
                logger.info("generationDataByNode json Info, node={}.", queryNode.getName());
            }
            else if(Constants.MODEL_FLAG_FOCUS.equals(queryNode.getNodeModel().getFlag())
                    || Constants.MODEL_FLAG_LIVE_NODE.equals(queryNode.getNodeModel().getFlag())
                    || Constants.MODEL_FLAG_LIVE.equals(queryNode.getNodeModel().getFlag())){
                htmlGenerator.makeInfo(site.getId(), queryNodeId,queryNode.getName(),true, user.getId());
                htmlGenerator.makeNode(site.getId(), queryNodeId,queryNode.getName(), true, user.getId(),null);
                logService.operation("opr.generationDataByNode", queryNode.getName(), null,queryNodeId,ip,user.getId(), site.getId());
                logger.info("generationDataByNode json Info, node={}.",queryNode.getName());

            }else if(Constants.SPECIAL_MANAGEMENT.equals(queryNode.getNodeModel().getFlag())){
                htmlGenerator.makeNode(site.getId(), queryNodeId,queryNode.getName(), false, user.getId(),null);
                logService.operation("opr.generationDataByNode", queryNode.getName(), null,queryNodeId,ip,user.getId(), site.getId());
                logger.info("generationDataByNode json Info, node={}.",queryNode.getName());
            }else{
//                htmlGenerator.makeInfo(site.getId(), queryNodeId,queryNode.getName(),true, user.getId());
                htmlGenerator.makeNode(site.getId(), queryNodeId,queryNode.getName(), true, user.getId(),null);
                logService.operation("opr.generationDataByNode", queryNode.getName(), null,queryNodeId,ip,user.getId(), site.getId());
                logger.info("generationDataByNode json Info, node={}.",queryNode.getName());
            }

        }
        ra.addAttribute("queryNodeId", nodeId);
        ra.addAttribute("returnUrl", jspUrl);
        ra.addAttribute("queryParentId",nodeId);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:"+returnUrl+".do";
    }

    /**
     * 生成启动页
     * @param ra
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationStartPage.do")
//    @RequiresRoles("super")
//    @RequiresPermissions("core:startPage:generationStartPage")
    public String generationStartPage(RedirectAttributes ra,
                                       HttpServletRequest request,org.springframework.ui.Model modelMap) {
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
	    Node rootnode=nodeQuery.findRoot(site.getId());
        htmlGenerator.generationStartPage(site,rootnode);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("opr.generationStartPage","启动页", null,rootnode.getId(),ip,user.getId(), site.getId());
        logger.info("generationStartPage json");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:/cmscp/ext/start_page/list.do";
    }

    /**
     * 生成版本更新数据
     * @param ra
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationAppversion.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:appversion:generationAppversion")
    public String generationAppversion(RedirectAttributes ra,
                                      HttpServletRequest request,org.springframework.ui.Model modelMap) {
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        Node rootnode=nodeQuery.findRoot(site.getId());
        htmlGenerator.generationAppversion(site,rootnode);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("opr.generationAppversion","版本更新信息", null,rootnode.getId(),ip,user.getId(), site.getId());
        logger.info("generationAppversion json");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:/cmscp/ext/appversion/list.do";
    }

    /**
     * 生成二维码数据
     * @param ra
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationQrcode.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:qrcode:generationQrcode")
    public String generationQrcode(RedirectAttributes ra,
                                       HttpServletRequest request,org.springframework.ui.Model modelMap) {
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        Node rootnode=nodeQuery.findRoot(site.getId());
        htmlGenerator.generationQrcode(site,rootnode);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("opr.generationQrcode","二维码信息", null,rootnode.getId(),ip,user.getId(), site.getId());
        logger.info("generationQrcode json");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:/cmscp/ext/qrcode/list.do";
    }

    /**
     * 生成悬浮层广告数据
     * @param ra
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationAdvertisement.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:advertisement:generationAdvertisement")
    public String generationAdvertisement(RedirectAttributes ra,
                                   HttpServletRequest request,org.springframework.ui.Model modelMap) {
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        Node rootnode=nodeQuery.findRoot(site.getId());
        htmlGenerator.generationAdvertisement(site,rootnode);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("opr.generationQrcode","悬浮层广告信息", null,rootnode.getId(),ip,user.getId(), site.getId());
        logger.info("generationQrcode json");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:/cmscp/ext/advertisement/list.do";
    }

    /**
     * 生成app服务配置json数据
     * @param ra
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationAppConfig.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:appconfig:generationAppConfig")
    public String generationAppConfig(RedirectAttributes ra,
                                   HttpServletRequest request,org.springframework.ui.Model modelMap) {
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        Node rootnode=nodeQuery.findRoot(site.getId());
        htmlGenerator.generationAppConfig(site,rootnode);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("opr.generationAppConfig","app服务配置", null,rootnode.getId(),ip,user.getId(), site.getId());
        logger.info("generationAppConfig json");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:/cmscp/ext/appconfig/list.do";
    }

    /**
     * 生成地市州服务配置json数据
     * @param ra
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationCityConfig.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:cityconfig:generationCityConfig")
    public String generationCityConfig(RedirectAttributes ra,
                                      HttpServletRequest request,org.springframework.ui.Model modelMap) {
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        Node rootnode=nodeQuery.findRoot(site.getId());
        htmlGenerator.generationCityConfig(site,rootnode);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("opr.generationCityConfig","地市州服务配置", null,rootnode.getId(),ip,user.getId(), site.getId());
        logger.info("generationCityConfig json");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:/cmscp/ext/cityconfig/list.do";
    }



	@Autowired
	private OperationLogService logService;
	@Autowired
	private ModelService modelService;
	@Autowired
	private NodeQueryService nodeQuery;
	@Autowired
	private HtmlService htmlService;
	@Autowired
	private HtmlGenerator htmlGenerator;
	@Autowired
	private InfoFulltextGenerator infoFulltextGenerator;
    @Autowired
    private SpecialFulltextGenerator specialFulltextGenerator;
}
